/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.hamacekj.dotaznikklient;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

/**
 * Otázka s odpovědí ve formě textového pole.
 * @author Jan Hamáček
 */
public class TextQuestion extends Question {
    
    public TextQuestion(BufferedWriter out, QuestionsQueue queue){
        super(out, queue);
        question = new StringBuilder();
    }

    @Override
    public void fromFirstLine(String firstLine) throws ProtocolException {
        try{
            String[] splitted = firstLine.split(" ", 3);
            if(!"ASK".equals(splitted[0]) || !"TEXT".equals(splitted[1])){
                throw new ProtocolException();
            }
            id = Integer.parseInt(splitted[2]);
        }catch(IndexOutOfBoundsException | NumberFormatException e){
            throw new ProtocolException();
        }
    }

    @Override
    public void addParam(String dataLine) throws ProtocolException {
        String[] splitted = dataLine.split(" ", 2);
        // rozhoduje o jaky typ parametru jde
        switch(splitted[0]){
            case "MSG":
                if(question.length() != 0){
                    question.append("<br>");
                }
                question.append(splitted[1]);
                break;
        }
    }

    @Override
    public String toText() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void invokeGUIAndSendReply() {
        try{
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    createAndShowGUI();
                }
            });
        }catch(InterruptedException | InvocationTargetException e){}
    }

    @Override
    public void cancel() {
        if(isDisplayed()){
            frame.setVisible(false);
        }
    }

    @Override
    public boolean isDisplayed() {
        if(frame == null){
            return false;
        }
        return frame.isVisible();
    }
    
    private void createAndShowGUI(){
        frame = new JFrame("Otázka");
        frame.setPreferredSize(new Dimension(200, 300));
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        Container root = frame.getContentPane();
        JLabel label;
        if(question.length() == 0){
            label = new JLabel("<html>Odpovězte na otázku</html>");
        }else{
            label = new JLabel("<html>"+question.toString()+"</html>");
        }
        final JTextArea reply = new JTextArea();
        reply.setFont(reply.getFont().deriveFont(12f));
        reply.setLineWrap(true);
        JButton ok = new JButton("Ok");
        ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ReplyThread t = new ReplyThread(reply.getText());
                frame.setVisible(false);
                // spoustim vlakno na odpoved a zavolani dalsi otazky.
                // Ted musi byt predchozi otazka zavrena, jinak by se nova nespustila
                t.start();
            }
        });
        root.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0; c.gridy = 0; c.gridwidth = 2;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(10, 10, 10, 10);
        root.add(label, c);
        c.gridy = 1; c.fill = GridBagConstraints.BOTH; c.weightx = 1; c.weighty = 1;
        root.add(reply, c);
        c.gridy = 2; c.gridx = 1; c.gridwidth = 0; c.weightx = 0; c.weighty = 0;
        c.anchor = GridBagConstraints.EAST; c.fill = GridBagConstraints.NONE;
        root.add(ok, c);
        frame.pack();
        frame.setAlwaysOnTop(true);
        frame.setVisible(true);
    }
    
    private class ReplyThread extends Thread{
        private String reply;
        
        public ReplyThread(String reply) {
            this.reply = reply;
        }
        
        @Override
        public void run(){
            unfinished.runNext();
            try{
                out.write("REPLY TEXT "+id);
                out.newLine();
                String[] replyArray = reply.split(System.lineSeparator());
                for(String s:replyArray){
                    if(!s.isEmpty()){
                        out.write("MSG "+s);
                        out.newLine();
                    }
                }
                out.write(".");
                out.newLine();
                out.flush();
            }catch(IOException e){
                // logovat
            }
        }
    }
    
    private JFrame frame = null;
    private StringBuilder question;
    
}
